package com.yishan;

import org.apache.http.HttpEntity;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.nio.charset.StandardCharsets;

/**
 *  httpClient 发送 get 请求
 *
 * @author: yishan
 * @Date: 2022/6/9 13:55
 **/
public class HttpClientDemo_02 {

    public static void main(String[] args) throws Exception {

        //可关闭的httpClient客户端
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String urlStr = "https://yishan99.github.io/";
        HttpGet httpGet = new HttpGet(urlStr);
        //解决httpclient被认为不是真人行为(爬虫的应用，防止检测，可不设置)
        httpGet.addHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36");
        //防盗链，value必须为该网站的网址(爬虫的应用，可不设置)
        httpGet.addHeader("Referer",urlStr);
        CloseableHttpResponse response = httpClient.execute(httpGet);
        //获取响应结果
        HttpEntity entity = response.getEntity();
        //对 httpEntity 操作的工具类
        String s = EntityUtils.toString(entity, StandardCharsets.UTF_8);
        System.out.println(s);
        // 确保流关闭
        EntityUtils.consume(entity);
        httpClient.close();

    }

}
